//
//  OAuthViewController.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/5.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
    //MARK: - 懒加载 webView
    private lazy var webView = UIWebView()
    //MARK: - 设置界面
    override func loadView() {
        view = webView
        //    设置代理
        webView.delegate = self
        //    设置标题
        title = "登陆新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oauthURL))
    }
    
    //MARK: -  监听方法
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc  private func autoFill(){
        let js = "document.getElementById('userId').value = '18810050075';" +
        "document.getElementById('passwd').value = 'mygitgoon0914';"
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
}

///MARK: - UIWebViewDelegate
extension OAuthViewController:UIWebViewDelegate{
    //    可重定向
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //        1 判断主机地址是否是www.baidu.com,不是允许访问
        guard let url = request.URL where url.host == "www.baidu.com" else{
            return true
        }
        //        2 判断目标是是否存在 Code=
        guard let quary = url.query where quary.hasPrefix("code=") else{
            print("取消访问")
            return false
        }
        //        3 提取 Code= 后内容
        let code = quary.substringFromIndex("code=".endIndex)
        print(quary)
        print("授权码是 " + code)
        //        4 加载 accessToken&获取用户信息
        UserAccountViewModel.sharedUserAccount.loadAccessToke(code) { (isSuccessed) -> () in
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("登陆失败")
                delay(1.0){
                    self.close()
                }
            }else{
              SVProgressHUD.dismiss()
//                发送通知,切换控制器
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName("TcgSwitchRootViewControllerNotification", object: "welcome")
                })
            }
        }
        return false
    }
    //   WebView 代理方法
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
